package com.twotiger.and.activity.user;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.activity.user.RegisterPage.ButtonTextFresh;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.CheckVcode;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.util.ActivitySwitcher;
import com.twotiger.and.util.RegexTool;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

/**
 * 
 * @Description: 
 * 找回密码 
 * @Author douxy
 * @Date 2015年8月15日 下午3:55:02
 */
public class FindPwdPage extends BaseActivity implements OnClickListener {

    private static final int SENDVCODEMSGSUCCES = 2;
    private static final int SENDVCODEMSGFAIL = 3;

    private static final int CHECKVCODEMSGSUCCES = 4;
    private static final int CHECKVCODEMSGFAIL = 5;

    private static final int TIMECOUNTMESSAGE = 6;

    private SubTitle subTitle;
    private HashMap<String, String> parm;

    private EditText phone;
    private Button code_btn;
    private EditText phone_code;
    private Button next;
    private ImageView iv_finish;
    private TextView tv_backtologin;
    private View findpwd_root;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.find_pwd_layout, null);
        if("forward".equals(getIntent().getStringExtra("isNeedAnim"))){
            ActivitySwitcher.animationInForward(view, getWindowManager());
        }
        return view;
    }

    @Override
    protected void findViewById(View view) {
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("找回登录密码");

        subTitle.hideBtns();
        subTitle.title_left_bt.setVisibility(View.VISIBLE);

        phone = (EditText) view.findViewById(R.id.phone);
        code_btn = (Button) view.findViewById(R.id.code_btn);
        phone_code = (EditText) view.findViewById(R.id.phone_code);
        next = (Button) view.findViewById(R.id.next);
        iv_finish = (ImageView)view.findViewById(R.id.iv_finish);
        tv_backtologin = (TextView) view.findViewById(R.id.tv_backtologin);
        findpwd_root = view.findViewById(R.id.findpwd_root);
        if (isLogin()) {
            phone.setText(application.getUser().phone);
            phone.setEnabled(false);
        }
    }

    @Override
    public void onClick(View view) {
        String phoneStr = phone.getText().toString().trim();
        String codeStr = phone_code.getText().toString().trim();
        switch (view.getId()) {
        case R.id.tv_backtologin: 
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
//            Intent intent = new Intent(this, LoginPage.class);
//            intent.putExtra("FROM", R.id.tv_backtologin);
//            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);

            final Intent intent1 = new Intent(getApplicationContext(), LoginPage.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            ActivitySwitcher.animationOutBack(findpwd_root, getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() {
                @Override
                public void onAnimationFinished() {
                    startNewActivity(intent1.putExtra("isNeedAnim", "back"), 0, 0, true);
                }
            });
            break;
        case R.id.iv_finish:
            finish();
            overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
            break;
        case R.id.next:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            ConstantDataUnit zz_sjh = getConstantDataByKey(Constants.zz_sjh);
            if(zz_sjh!=null){
                if (TextUtils.isEmpty(phoneStr) || !RegexTool.match(zz_sjh.getVal(), phoneStr)) { //手机号正则匹配
                    showToast("请输入有效的手机号");
                    return;
                }
            }else {
                if (TextUtils.isEmpty(phoneStr) || !RegexTool.regexPhoneNumber(phoneStr)) { //手机号正则匹配
                    showToast("请输入有效的手机号");
                    return;
                }
            }
            if (TextUtils.isEmpty(codeStr)) {
                showToast("请输验证码");
                return;
            }
            //进行验证码的校验
            checkVcode(phoneStr, codeStr);

            break;
        case R.id.code_btn:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (TextUtils.isEmpty(phoneStr)) {
                showToast("请输入手机号");
                return;
            }
            ConstantDataUnit zz_sjh_1 = getConstantDataByKey(Constants.zz_sjh);
            if(zz_sjh_1!=null){
                if (!RegexTool.match(zz_sjh_1.getVal(), phoneStr)) {
                    showToast("请输入有效手机号");
                    return;
                }
            }else {
                if (!RegexTool.regexPhoneNumber(phoneStr)) {
                    showToast("请输入有效手机号");
                    return;
                }
            }
            getauthcode(phoneStr);
            break;
        }
    }

    private void checkVcode(String phoneStr, String codeStr) {
        parm.clear();
        parm.put("phone", phoneStr);
        parm.put("code", codeStr);
        getDate(parm, Constants.VERIFYCAP, handler, CHECKVCODEMSGSUCCES, CHECKVCODEMSGFAIL,
            false, false, false);

    }

    private void getauthcode(String phone) {
        parm.clear();
        parm.put("phone", phone);
        parm.put("type", "sms");
        parm.put("function", "forget_pwd");
        getDate(parm, Constants.CAPTCHA, handler, SENDVCODEMSGSUCCES, SENDVCODEMSGFAIL, true,
            false, false);
    }

    @Override
    protected void setListener() {
        tv_backtologin.setOnClickListener(this);
        iv_finish.setOnClickListener(this);
        code_btn.setOnClickListener(this);
        next.setOnClickListener(this);
        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case SENDVCODEMSGSUCCES:
                    Basebean responseInfo = JSONObject
                        .parseObject((String) msg.obj, Basebean.class);
                    if (responseInfo.isOk()) {
                        showToast("验证码已经发送至您的手机，注意查收...");
                        timer_show();
                    } else {
                        showToast(responseInfo.codeDesc);
                    }
                    break;
                case SENDVCODEMSGFAIL:
                    showToast("请求失败...");
                    break;
                case CHECKVCODEMSGSUCCES:
                    Basebean result_v = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_v.isOk()) {
                        CheckVcode responseCheckVcodeInfo = JSONObject.parseObject(result_v.data,
                            CheckVcode.class);
                        String token = responseCheckVcodeInfo.getToken();
//                        Intent intent = new Intent(FindPwdPage.this, FindPwdNext.class);
//                        intent.putExtra("token", token);
//                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);
                        
                        final Intent intent = new Intent(FindPwdPage.this, FindPwdNext.class);
                        intent.putExtra("token", token);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        ActivitySwitcher.animationOutForward(findpwd_root, getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() {
                            @Override
                            public void onAnimationFinished() {
                                startNewActivity(intent.putExtra("isNeedAnim", "forward"), 0, 0, true);
                            }
                        });
                    } else {
                        showToast(result_v.codeDesc);
                    }
                    break;
                case TIMECOUNTMESSAGE:
                    code_btn.setEnabled(true);
                    // 设置为原有的text
                    code_btn.setText(btnMsg);
                    // timer 取消执行
                    timer.cancel();
                    break;
                case CHECKVCODEMSGFAIL:
                    showToast("请求失败...");
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        
        phone_code.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }
            
            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s) || s.length() < 6 || StringUtils.isEmpty(phone.getText().toString().trim())) {
                    next.setEnabled(false);
                } else {
                    next.setEnabled(true);
                }
            }
        });
        
    }

    // 倒计时用计数
    private int time;
    // 按钮上的文字
    private String btnMsg = "";
    private Timer timer;

    @SuppressLint("NewApi")
    private void timer_show() {
        time = 60;
        btnMsg = code_btn.getText().toString();
        // 设置按钮不可点击
        code_btn.setEnabled(false);
        //      regist_verification_bt.setPadding(18, 10, 18, 10);
        //      regist_verification_bt.setBackgroundColor(mContext.getResources().getColor(R.color.half_gray));
        timer = new Timer();
        // 点击1毫秒开始执行，没个一秒执行一次
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                int i = getInt();
                code_btn.post(new ButtonTextFresh(i));
                // 若倒计时到0时
                if (i == 0) {
                    handler.sendEmptyMessage(TIMECOUNTMESSAGE);
                }
            }
        }, 1, 1000);
    }

    /**
     * 获取倒计时的计数
     * 
     * @return
     */
    private int getInt() {
        return time--;
    }

    class ButtonTextFresh implements Runnable {

        private int iMsg;

        public ButtonTextFresh(int iMsg) {
            this.iMsg = iMsg;
        }

        @Override
        public void run() {
            code_btn.setText(btnMsg + "(" + iMsg + ")");
        }
    }

    @Override
    protected void processLogic() {
        parm = getParm();
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

}
